package cn.itcast.user.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.user.domain.User;
import cn.itcast.user.service.UserException;
import cn.itcast.user.service.UserService;
import cn.itcast.utils.CommonUtils;

/**
 * @author yogamimi  E-mail: wuzuyixm@163.com
 * @version 创建时间：Jan 7, 2019  1:34:57 AM
 * tags
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		System.out.println("RegistServlet called!");
		//依赖UserService	
		UserService userService = new UserService();
		//封装表单数据
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		//调用regist()注册用户
		//如果得到异常，保存异常信息到request域中，并转发到regist.jsp页面
		//如果没有异常，输出注册成功！
		try {
			userService.regist(form);
			response.getWriter().print("<h1 color=red>注册成功！</h><br/><a href='" +
					request.getContextPath() + "/user/login.jsp" + "'>点击这里去登录</a>");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("user", form);
			//转发不用带项目名
			request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
		}
	}
}